package com.gitee.chessboard.jdbc;

import com.gitee.chessboard.jdbc.executor.SqlExecutor;
import com.gitee.chessboard.jdbc.executor.SqlExecutorFactory;
import com.gitee.chessboard.jdbc.parser.ParserHandler;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * jdbc的管理器
 *
 * @author 敲代码的旺财
 * @date 2021/11/18 17:32
 */
public class JdbcManager {
    /**
     * 类的解析处理器
     * Map<类对象，解析结果>
     */
    private Map<Class<?>, ParserHandler> parserHandler;
    private String driverClassName;
    private String url;
    private String userName;
    private String password;

    /**
     * mybatis的sql执行工厂
     */
    private SqlSessionFactory mybatisSqlSessionFactory;

    private SqlExecutor sqlExecutor;

    public JdbcManager(String driverClassName, String url, String userName, String password) {
        this.driverClassName = driverClassName;
        this.url = url;
        this.userName = userName;
        this.password = password;
        this.parserHandler = new ConcurrentHashMap<>();
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public SqlSessionFactory getMybatisSqlSessionFactory() {
        return mybatisSqlSessionFactory;
    }

    public void setMybatisSqlSessionFactory(SqlSessionFactory mybatisSqlSessionFactory) {
        this.mybatisSqlSessionFactory = mybatisSqlSessionFactory;
    }

    public SqlExecutor getSqlExecutor() {
        if (sqlExecutor == null) {
            this.sqlExecutor = new SqlExecutorFactory(this).get();
        }
        return sqlExecutor;
    }

    public synchronized ParserHandler getParserHandler(Object obj) {
        ParserHandler parserHandler = this.parserHandler.get(obj.getClass());
        if (parserHandler == null) {
            parserHandler = new ParserHandler(obj, this);
        }
        return parserHandler;
    }
}
